<template>
    <div class="app-container">
      <div class="search-bar">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="设备名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入设备名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" style="width: 240px" clearable>
              <el-option label="空闲" value="free" />
              <el-option label="忙碌" value="busy" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="search" @click="handleQuery()">搜索</el-button>
            <el-button icon="refresh" @click="handleResetQuery()">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
  
      <el-card shadow="never">
        <div class="mb-[10px] topCard">
          <div style="" class="dataOverview">
            <div style="display: flex;">
              <div class="flex" v-for="item, index in dataOverview.all" :key="index">
                <div style="min-width:90px;text-align: right;">{{ item.label }}：</div>
                <div style="min-width: 80px;">{{ item.value }}</div>
              </div>
            </div>
            <div class="flex">
              <div class="flex" v-for="item, index in dataOverview.today" :key="index">
                <div style="min-width:90px;text-align: right;">{{ item.label }}：</div>
                <div style="min-width: 80px;">{{ item.value }}</div>
              </div>
            </div>
          </div>
          <div class="btngroup">
            <el-button style="margin-top: 15px; margin-right: 10px;" type="danger" icon="delete" size="small" @click="handleDelete()">批量删除</el-button>
            <auto-refresh ref="autoRefreshRef" :time="5" @task="getList"/>
          </div>
        </div>
  
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" fixed="left" />
          <el-table-column label="设备名称" prop="name" fixed="left" min-width="100" />
          <el-table-column label="总数 / 当天" prop="total" min-width="100">
            <template #default="{ row }">{{ row.total[0] }} / {{ row.total[1] }}</template>
          </el-table-column>
          <el-table-column label="导出总数 / 当天" prop="exported" min-width="140">
            <template #default="{ row }">{{ row.exported[0] }} / {{ row.exported[1] }}</template>
          </el-table-column>
          <el-table-column label="未导出总数 / 当天" prop="exported" min-width="150">
            <template #default="{ row }">{{ row.unexported[0] }} / {{ row.unexported[1] }}</template>
          </el-table-column>
          <el-table-column label="成功总数 / 当天" prop="success" min-width="130">
            <template #default="{ row }">{{ row.success[0] }} / {{row.success[1]}}</template>
          </el-table-column>
          <el-table-column label="失败总数 / 当天" prop="fail" min-width="130">
            <template #default="{ row }">{{ row.total[0] - row.success[0] }} / {{ row.total[1] - row.success[1] }}</template>
          </el-table-column>
          <el-table-column label="上次导出" prop="lastExport" min-width="150">
            <template #default="{ row }">{{ row.lastExport ? formatDate(row.lastExport) : '--' }}</template>
          </el-table-column>
          <el-table-column label="上次上传" prop="lastUpload" min-width="150">
            <template #default="{ row }">{{ row.lastUpload ? formatDate(row.lastUpload) : '--' }}</template>
          </el-table-column>
  
          <el-table-column label="状态" prop="status">
            <template #default="{ row }">
              <el-tag type="success" v-if="row.status == 'free'">空闲</el-tag>
              <el-tag type="warning" v-else>忙碌</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" prop="status" fixed="right" width="120">
            <template #default="{ row, $index }">
              <el-button v-if="$index !== 0 || paging.page !== 1" type="primary" link size="small" @click="handlePinApi(row)">置顶</el-button>
              <el-button type="primary" link size="small" @click="handleDelete(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            v-model:current-page="paging.page"
            v-model:page-size="paging.size"
            :page-sizes="[10, 20, 30, 50, 100]"
            :size="paging.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="paging.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </template>
  
  
  <script setup>
  import AutoRefresh from "@/components/autoRefresh/index.vue"
  import { listApi, pinApi, deleteApi } from '@/api/equipmentManagement/device.api'
  import { formatDate } from "@/utils";
  import { useParamStore } from '@/store'
  
  const props = defineProps({
    appType: {
      type: String,
      required: false,
      default: 'WA'
    }
  })
  
  const route = useRoute();
  const { setParams, getParams, removeFalsyValues } = useParamStore()
  const name = route.fullPath
  onMounted(() => {
    if(!!getParams(name)) {
      queryParams.value = getParams(name)
    }
    getList()
  })
  
  const paging = ref({
    size: 10,
    page: 1,
    total: 0,
  })
  
  const handleSizeChange = (e) => {
    paging.value.size = e
    paging.value.page = 1
    getList()
  }
  const handleCurrentChange = (e) => {
    paging.value.page = e
    getList()
  }
  
  const ids = ref([])
  const loading = ref(false)
  const tableData = ref([])
  const queryParams = ref({
    name: void undefined,
    status: void undefined,
  })
  const handleQuery = () => {
    paging.value.page = 1
    paging.value.size = 10
    setParams(queryParams.value, name)
    getList()
  }
  const handleSelectionChange = (e) => {
    ids.value = e.map(item => item.id)
  }
  
  const editFormRef = ref(null)
  const handleAddClick = () => {
    editFormRef.value.handleOpen()
  }
  
  const queryFormRef = ref(null)
  const handleResetQuery = () => {
    queryFormRef.value.resetFields()
    handleQuery()
  }

  const handlePinApi = (row) => {
    pinApi({ id: row.id }).then(res => {
      paging.value.page = 1
      getList()
      ElMessage({
        type: 'success',
        message: '置顶成功',
      })
    })
  }
  
  const resetPassword = (row) => {
    editFormRef.value.handleOpen(row)
  }
  
  const handleDelete = (e) => {
    if(!e) {
      ElMessageBox.confirm(
        '是否确定删除选择行?',
        '温馨提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          deleteApi({ ids: ids.value }).then(res => {
            handleQuery()
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
          })
        })
      return
    }
    ElMessageBox.confirm(
        '是否确定删除该行?',
        '温馨提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          deleteApi({ ids: [e] }).then(res => {
            handleQuery()
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
          })
        })
  }
  
  const dataOverview = ref({})
  const busies = ref(null)
  const valids = ref(null)
  const autoRefreshRef = ref(null)
  const getList = () => {
    loading.value = true
    let name = void undefined
    if(queryParams.value.name?.trim()) {
      name = queryParams.value.name.split(/[,，]/).filter(item => item.trim() !== '')
    }
    listApi({
      page: paging.value.page,
      size: paging.value.size,
      name: name || void undefined,
      status: queryParams.value.status || void undefined,
      app: props.appType,
    }).then(res => {

      console.log(res, 'list');
      
      loading.value = false
      busies.value = res?.busies || 0
      valids.value = res?.valids || 0
      tableData.value = res?.devices || []
      paging.value.total = res?.count || 0
      autoRefreshRef.value.start()
      if(tableData.value.length > 0) {
        //  / 今日账号数
        dataOverview.value = {
          all: [
            {
              label: '账号总数',
              value: res.total[0]
            }, 
            {
              label: '失败总数',
              value: res.total[0] - res.success[0]
            }, 
            {
              label: '成功总数',
              value: res.success[0]
            }, 
  
            {
              label: '导出总数',
              value: res.exported[0]
            },
            {
              label: '未导出总数',
              value: res.unexported[0]
            }
          ],
          today: [
            {
              label: '今日账号数',
              value: res.total[1]
            }, 
            {
              label: '今日失败数',
              value: res.total[1] - res.success[1]
            }, 
            {
              label: '今日成功数',
              value: res.success[1]
            }, 
  
            {
              label: '今日导出数',
              value: res.exported[1]
            },
            {
              label: '今日未导出数',
              value: res.unexported[1]
            }
          ]
        }
      }
    }).finally(res => {
      loading.value = false
    })
  }
  </script>
  
  <style scoped lang="scss">
  .pagination{
    display: flex;
    justify-content: flex-end;
    margin-top: 15px;
  }
  .autoRefresh{
    display: flex;
    align-items: center;
    margin-top: 15px;
  }
  .dataOverview{
    background: #409eff30; 
    color: #409eff;
    padding: 10px; 
    border-radius: 5px;
    width: 100%;
    overflow: auto;
    font-size: 12px;
  }
  .btngroup{
    display: flex;
    align-items: center;
  }
  </style>
  